package org.example.backend.service.impl;

import jakarta.annotation.Resource;
import org.example.backend.dto.PolicyInfoDTO;
import org.example.backend.dto.PageResult;
import org.example.backend.entity.PolicyInfo;
import org.example.backend.mapper.PolicyInfoMapper;
import org.example.backend.service.PolicyInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Service
public class PolicyInfoServiceImpl implements PolicyInfoService {
    @Resource
    private final PolicyInfoMapper policyInfoMapper;

    public PolicyInfoServiceImpl(PolicyInfoMapper policyInfoMapper) {
        this.policyInfoMapper = policyInfoMapper;
    }

    /**
     * 查询政策库真实总数
     */
    @Override
    public int countAllPolicies() {
        return policyInfoMapper.countAllPolicies();
    }

    @Override
    public PageResult<PolicyInfoDTO> getPoliciesByPage(int page, int size, String keyword, String category, String department, String region, String dateFrom, String dateTo, List<String> tags, String status, String sortBy, String sortOrder) {
        // 参数验证：确保 page 至少为 1，size 至少为 1
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        
        int offset = (page - 1) * size;
        List<PolicyInfoDTO> data = policyInfoMapper.selectPoliciesByPage(keyword, category, department, region, dateFrom, dateTo, tags, status, sortBy, sortOrder, size, offset);
        
        // 处理聚合的标签数组字段
        data.forEach(dto -> {
            processAggregatedLabels(dto);
        });
        
        int total = policyInfoMapper.countPolicies(keyword, category, department, region, dateFrom, dateTo, tags, status);
        return new PageResult<>(data, total);
    }

    @Override
    public PolicyInfoDTO getPolicyById(String policyId) {
        PolicyInfo entity = null;
        try {
            entity = policyInfoMapper.selectById(policyId);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("selectById error, policyId=" + policyId + ", msg=" + e.getMessage());
            return null;
        }
        if (entity == null) return null;
        
        PolicyInfoDTO dto = new PolicyInfoDTO();
        try {
            // 先处理Entity的聚合字段
            processEntityAggregatedLabels(entity);
            
            // 复制属性
            BeanUtils.copyProperties(entity, dto);
            
            // 处理DTO的聚合字段
            processAggregatedLabels(dto);
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("BeanUtils.copyProperties error, policyId=" + policyId + ", msg=" + e.getMessage());
            return null;
        }
        
        // 最细分地址赋值
        try {
            dto.setMostDetailedAddress(getMostDetailedAddress(entity));
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("setMostDetailedAddress error, policyId=" + policyId + ", msg=" + e.getMessage());
        }
        return dto;
    }

    @Override
    public List<PolicyInfoDTO> getAllPolicies() {
        return policyInfoMapper.selectAll()
                .stream()
                .map(entity -> {
                    PolicyInfoDTO dto = new PolicyInfoDTO();
                    
                    // 处理Entity的聚合字段
                    processEntityAggregatedLabels(entity);
                    
                    // 复制属性
                    BeanUtils.copyProperties(entity, dto);
                    
                    // 处理DTO的聚合字段
                    processAggregatedLabels(dto);
                    
                    dto.setMostDetailedAddress(getMostDetailedAddress(entity));
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<PolicyInfoDTO> filterPolicies(String keyword, String category, String department, String region, String dateFrom, String dateTo, List<String> tags, String status) {
        List<PolicyInfoDTO> results = policyInfoMapper.filterPolicies(keyword, category, department, region, dateFrom, dateTo, tags, status);
        
        // 处理聚合的标签数组字段
        results.forEach(dto -> {
            processAggregatedLabels(dto);
        });
        
        return results;
    }

    @Override
    public List<PolicyInfoDTO> fuzzySearchPolicies(String keyword) {
        return policyInfoMapper.fuzzySearchPolicies(keyword)
                .stream()
                .map(entity -> {
                    PolicyInfoDTO dto = new PolicyInfoDTO();
                    
                    // 处理Entity的聚合字段
                    processEntityAggregatedLabels(entity);
                    
                    // 复制属性
                    BeanUtils.copyProperties(entity, dto);
                    
                    // 处理DTO的聚合字段
                    processAggregatedLabels(dto);
                    
                    dto.setMostDetailedAddress(getMostDetailedAddress(entity));
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 处理Entity的聚合标签字段：将字符串转为List
     */
    private void processEntityAggregatedLabels(PolicyInfo entity) {
        try {
            // 处理GB标签
            if (entity.getGbIndustry2ListString() != null && !entity.getGbIndustry2ListString().trim().isEmpty()) {
                List<String> gbList = Arrays.stream(entity.getGbIndustry2ListString().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
                entity.setGbIndustry2List(gbList);
            } else {
                entity.setGbIndustry2List(new ArrayList<>());
            }
            
            // 处理ZX标签
            if (entity.getZxIndustry2ListString() != null && !entity.getZxIndustry2ListString().trim().isEmpty()) {
                List<String> zxList = Arrays.stream(entity.getZxIndustry2ListString().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
                entity.setZxIndustry2List(zxList);
            } else {
                entity.setZxIndustry2List(new ArrayList<>());
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("处理Entity聚合标签失败: " + e.getMessage());
            entity.setGbIndustry2List(new ArrayList<>());
            entity.setZxIndustry2List(new ArrayList<>());
        }
    }

    /**
     * 处理DTO的聚合标签字段：将字符串转为List，并合并到tags字段
     */
    private void processAggregatedLabels(PolicyInfoDTO dto) {
        try {
            List<String> allTags = new ArrayList<>();
            
            // 处理GB标签
            if (dto.getGbIndustry2ListString() != null && !dto.getGbIndustry2ListString().trim().isEmpty()) {
                List<String> gbList = Arrays.stream(dto.getGbIndustry2ListString().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
                dto.setGbIndustry2List(gbList);
                allTags.addAll(gbList);
            } else {
                dto.setGbIndustry2List(new ArrayList<>());
            }
            
            // 处理ZX标签
            if (dto.getZxIndustry2ListString() != null && !dto.getZxIndustry2ListString().trim().isEmpty()) {
                List<String> zxList = Arrays.stream(dto.getZxIndustry2ListString().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
                dto.setZxIndustry2List(zxList);
                allTags.addAll(zxList);
            } else {
                dto.setZxIndustry2List(new ArrayList<>());
            }
            
            // 兼容处理：如果已有tags字段，则合并
            if (dto.getTags() != null && !dto.getTags().isEmpty()) {
                allTags.addAll(dto.getTags());
            }
            
            // 去重并设置tags
            dto.setTags(allTags.stream().distinct().collect(Collectors.toList()));
            
            // 设置最细分地址
            dto.setMostDetailedAddress(getMostDetailedAddress(dto));
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("处理DTO聚合标签失败: " + e.getMessage());
            // 设置空值避免null异常
            dto.setGbIndustry2List(new ArrayList<>());
            dto.setZxIndustry2List(new ArrayList<>());
            if (dto.getTags() == null) {
                dto.setTags(new ArrayList<>());
            }
        }
    }

    // 工具方法：自动选取最细分地址
    // 地址层级：address1(国家) -> address2(省份) -> address3(盟市) -> address4(区县) -> address5 -> address6(最细分)
    private String getMostDetailedAddress(Object obj) {
        String[] addresses = null;
        if (obj instanceof PolicyInfo) {
            addresses = new String[] {
                ((PolicyInfo)obj).getAddress6(),  // 最细分级别
                ((PolicyInfo)obj).getAddress5(),  // 更细分级别
                ((PolicyInfo)obj).getAddress4(),  // 区县
                ((PolicyInfo)obj).getAddress3(),  // 盟市
                ((PolicyInfo)obj).getAddress2(),  // 省份
                ((PolicyInfo)obj).getAddress1()   // 国家
            };
        } else if (obj instanceof PolicyInfoDTO) {
            addresses = new String[] {
                ((PolicyInfoDTO)obj).getAddress6(),  // 最细分级别
                ((PolicyInfoDTO)obj).getAddress5(),  // 更细分级别
                ((PolicyInfoDTO)obj).getAddress4(),  // 区县
                ((PolicyInfoDTO)obj).getAddress3(),  // 盟市
                ((PolicyInfoDTO)obj).getAddress2(),  // 省份
                ((PolicyInfoDTO)obj).getAddress1()   // 国家
            };
        }
        if (addresses != null) {
            for (String addr : addresses) {
                if (addr != null && !addr.trim().isEmpty()) {
                    return addr.trim();
                }
            }
        }
        return null;
    }

    @Override
    public List<PolicyInfoDTO> getRelatedPolicies(String policyId, int limit) {
        PolicyInfoDTO cur = getPolicyById(policyId);
        if (cur == null) return java.util.Collections.emptyList();
        
        List<PolicyInfoDTO> candidates = getAllPolicies().stream()
                .filter(p -> !p.getPolicyId().equals(cur.getPolicyId()))
                .collect(Collectors.toList());
                
        return candidates.stream()
            .map(p -> {
                int score = 0;
                // 标签交集加分
                List<String> tagsA = p.getTags() != null ? p.getTags() : java.util.Collections.emptyList();
                List<String> tagsB = cur.getTags() != null ? cur.getTags() : java.util.Collections.emptyList();
                long tagMatch = tagsA.stream().filter(tagsB::contains).count();
                if (!tagsA.isEmpty() && !tagsB.isEmpty()) {
                    double tagScore = 5.0 * tagMatch / Math.max(tagsA.size(), tagsB.size());
                    score += (int) Math.round(tagScore);
                }
                p.setGbIndustry2(String.valueOf(score)); // 用gbIndustry2临时存分数
                return p;
            })
            .sorted((a, b) -> Integer.parseInt(b.getGbIndustry2()) - Integer.parseInt(a.getGbIndustry2()))
            .limit(limit)
            .collect(Collectors.toList());
    }
    
    @Override
    public List<PolicyInfoDTO> getBatchPoliciesByIds(List<String> policyIds) {
        if (policyIds == null || policyIds.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        
        return policyIds.stream()
                .map(this::getPolicyById)
                .filter(java.util.Objects::nonNull)
                .collect(Collectors.toList());
    }
    
    @Override
    public java.util.Map<String, Object> getPolicyStatisticsForComparison(List<String> policyIds) {
        java.util.Map<String, Object> statistics = new java.util.HashMap<>();
        
        try {
            // 获取政策详情
            List<PolicyInfoDTO> policies = getBatchPoliciesByIds(policyIds);
            
            statistics.put("policies", policies);
            statistics.put("total_count", policies.size());
            
            // 计算各种统计指标
            java.util.Map<String, Integer> typeStats = new java.util.HashMap<>();
            java.util.Map<String, Integer> levelStats = new java.util.HashMap<>();
            java.util.Map<String, Integer> validityStats = new java.util.HashMap<>();
            java.util.Map<String, Integer> departmentStats = new java.util.HashMap<>();
            
            for (PolicyInfoDTO policy : policies) {
                String type = policy.getType();
                Integer level = policy.getLevel();
                Boolean validity = policy.getValidity();
                String department = policy.getDepartment();
                
                typeStats.merge(type != null ? type : "未知", 1, Integer::sum);
                levelStats.merge(level != null ? level.toString() : "未知", 1, Integer::sum);
                validityStats.merge(validity != null ? (validity ? "有效" : "无效") : "未知", 1, Integer::sum);
                departmentStats.merge(department != null ? department : "未知", 1, Integer::sum);
            }
            
            statistics.put("type_distribution", typeStats);
            statistics.put("level_distribution", levelStats);
            statistics.put("validity_distribution", validityStats);
            statistics.put("department_distribution", departmentStats);
            
        } catch (Exception e) {
            System.err.println("获取政策统计信息失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return statistics;
    }
    
    @Override
    public java.util.Map<String, Object> getPolicyGeoDistribution(List<String> policyIds) {
        java.util.Map<String, Object> geoData = new java.util.HashMap<>();
        
        try {
            // 获取政策详情
            List<PolicyInfoDTO> policies = getBatchPoliciesByIds(policyIds);
            
            java.util.Map<String, Integer> countryStats = new java.util.HashMap<>();      // address1: 国家
            java.util.Map<String, Integer> provinceStats = new java.util.HashMap<>();    // address2: 省份
            java.util.Map<String, Integer> cityStats = new java.util.HashMap<>();        // address3: 盟市
            java.util.Map<String, Integer> districtStats = new java.util.HashMap<>();    // address4: 区县
            java.util.Map<String, Integer> address5Stats = new java.util.HashMap<>();    // address5: 更细分级别
            java.util.Map<String, Integer> address6Stats = new java.util.HashMap<>();    // address6: 最细分级别
            
            for (PolicyInfoDTO policy : policies) {
                String country = policy.getAddress1();      // 国家
                String province = policy.getAddress2();     // 省份
                String city = policy.getAddress3();         // 盟市
                String district = policy.getAddress4();     // 区县
                String addr5 = policy.getAddress5();        // 更细分级别
                String addr6 = policy.getAddress6();        // 最细分级别
                
                if (country != null && !country.trim().isEmpty()) {
                    countryStats.merge(country, 1, Integer::sum);
                }
                if (province != null && !province.trim().isEmpty()) {
                    provinceStats.merge(province, 1, Integer::sum);
                }
                if (city != null && !city.trim().isEmpty()) {
                    cityStats.merge(city, 1, Integer::sum);
                }
                if (district != null && !district.trim().isEmpty()) {
                    districtStats.merge(district, 1, Integer::sum);
                }
                if (addr5 != null && !addr5.trim().isEmpty()) {
                    address5Stats.merge(addr5, 1, Integer::sum);
                }
                if (addr6 != null && !addr6.trim().isEmpty()) {
                    address6Stats.merge(addr6, 1, Integer::sum);
                }
            }
            
            geoData.put("country_distribution", countryStats);     // 国家分布
            geoData.put("province_distribution", provinceStats);   // 省份分布
            geoData.put("city_distribution", cityStats);           // 盟市分布
            geoData.put("district_distribution", districtStats);   // 区县分布
            geoData.put("address5_distribution", address5Stats);   // 更细分级别分布
            geoData.put("address6_distribution", address6Stats);   // 最细分级别分布
            geoData.put("policies", policies);
            
        } catch (Exception e) {
            System.err.println("获取政策地理分布失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return geoData;
    }
}
